import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import '../common/tools.dart';

class ShowPhotoView extends StatelessWidget {
  const ShowPhotoView(this.path, {super.key, this.isNetImg = false});

  final String path;
  final bool isNetImg;
  @override
  Widget build(BuildContext context) {
    if (isNetImg) {
      return GestureDetector(
        onTap: Get.back,
        child: PhotoView(
          imageProvider: NetworkImage(path),
        ),
      );
    }
    if (path.isEmpty || !File(path).existsSync()) {
      Toasts.showToast('没有图片！');
      Get.back();
    }
    return GestureDetector(
      onTap: Get.back,
      child: PhotoView(
        imageProvider: FileImage(File(path)),
      ),
    );
  }
}

class ShowPhotoGallery extends StatelessWidget {
  const ShowPhotoGallery(
      {super.key,
      this.images = const [],
      this.index = 0,
      this.imagePaths = const []});

  final List<File> images;
  final List<String> imagePaths;
  final int index;

  @override
  Widget build(BuildContext context) {
    if (imagePaths.isEmpty && images.isEmpty) {
      Toasts.showToast('没有图片！');
      Get.back();
    }
    int currentIndex = index;
    return WillPopScope(
      onWillPop: () async {
        Get.back(result: currentIndex);
        return false;
      },
      child: GestureDetector(
        onTap: () => Get.back(result: currentIndex),
        child: SizedBox(
            height: 100,
            child: PhotoViewGallery.builder(
              itemCount: imagePaths.isEmpty ? images.length : imagePaths.length,
              pageController: PageController(initialPage: index),
              builder: (BuildContext context, int index) {
                return PhotoViewGalleryPageOptions(
                  imageProvider: FileImage(imagePaths.isEmpty
                      ? images[index]
                      : File(imagePaths[index])),
                  initialScale: PhotoViewComputedScale.contained,
                  // heroAttributes:
                  //     PhotoViewHeroAttributes(tag: images[index].path),
                );
              },
              onPageChanged: (index) {
                currentIndex = index;
              },
            )),
      ),
    );
  }
}
